const jwt = require('jsonwebtoken');
const { workorder_collection } = require('../config')
const { obd_collection } = require('../config')
const { staff_collection } = require('../config')
const { obd_modify_collection } = require('../config')
const common = require('./common');
const { db } = require('../config')
const { command } = require('../config')
const _ = command
const zdProcess = ["综调发起", "班长审批", "装维站审批", "综调审批", "通知新装维"];
const bzProcess = ["班长发起", "综调发起", "主管审批", "装维站审批", "综调审批", "通知新旧装维"];
exports.main = async (event, context) => {
    const data = event;
    // 1.查询工单当前流程
    // 2.如果同意，则根据工单类型、是否同意判断下一个工单流程是什么，并将流程追加到历史流程
    // 3.如果不同意，则根据历史流程回到上一个
    wordOrder = await db.collection(workorder_collection).doc(data.id).get();
    wordOrder = wordOrder.data[0];
    currentProcess = wordOrder.currentProcess;
    reqProcess = data.currentProcess;
    if (currentProcess != reqProcess) {
        return { "code": 1, message: "工单已不在“" + reqProcess + "”流程，请刷新页面！", data: data.id }
    }
    const type = wordOrder.type;
    update = {};
    status = '';
    nextPosition = ''
    nextProcess = ''
    changeNewZw = '';
    if ('agreeOrNot' in data && data.agreeOrNot !== undefined) {
        const agreeOrNot = data.agreeOrNot;
        const obdAndStaffString = wordOrder.obdAndStaff;
        if (agreeOrNot == '同意') {
            if (type == '综调发起') {
                if (currentProcess == '综调发起') {
                    nextProcess = '班长审批'
                    update.modifyStaff = data.modifyStaff;
                    const newStaff = JSON.parse(data.modifyStaff)
                    update.region = newStaff.region;
                    update.grid = newStaff.grid
                    // 判断是否修改了离职装维人员
                    var woModifyStaff = JSON.parse(wordOrder.modifyStaff)
                    if (woModifyStaff.account != newStaff.account) {
                        var resOld = await db.collection(staff_collection).where({ account: woModifyStaff.account }).update({ status: "在职" });
                        var resNew = await db.collection(staff_collection).where({ account: newStaff.account }).update({ status: "离职" });
                    }
                } else if (currentProcess == '班长审批') {
                    nextProcess = '装维站审批'
                } else if (currentProcess == '装维站审批') {
                    nextProcess = '综调审批'
                } else if (currentProcess == '综调审批') {
                    reqObdAndStaff = data.obdAndStaff
                    const obdAndStaffs = JSON.parse(reqObdAndStaff);
                    if (wordOrder.status != '已完成') {
                        await db.collection(workorder_collection).doc(data.id).update({ 'status': '已完成' });
                        for (obdAndStaff of obdAndStaffs) {
                            await db.collection(obd_collection).where({ _id: obdAndStaff._id }).update({
                                staff: obdAndStaff.newStaffAccount,
                                staffName: obdAndStaff.newStaffName,
                                isNewAdd: "否",
                                grid: wordOrder.grid
                            })
                            await db.collection(obd_modify_collection).add({
                                obd_id: obdAndStaff._id,
                                obdID: obdAndStaff.obdId,
                                obdName: obdAndStaff.fgqmc,
                                oldStaffName: obdAndStaff.oldStaffName,
                                oldStaffAccount: obdAndStaff.oldStaffAccount,
                                newStaffName: obdAndStaff.newStaffName,
                                newStaffAccount: obdAndStaff.newStaffAccount,
                                workOrderId: data.id,
                                grid: wordOrder.grid,
                                createDateTime: common.getDateTime(),
                                workOrderCreator: wordOrder.creator
                            })
                        }
                    }
                    nextProcess = '通知新装维'
                }
            } else {
                if (currentProcess == '班长发起') {
                    nextProcess = '主管审批'
                } else if (currentProcess == '主管审批') {
                    nextProcess = '装维站审批'
                } else if (currentProcess == '装维站审批') {
                    nextProcess = '综调审批'
                } else if (currentProcess == '综调审批') {
                    reqObdAndStaff = data.obdAndStaff
                    const obdAndStaffs = JSON.parse(reqObdAndStaff);
                    if (wordOrder.status != '已完成') {
                        await db.collection(workorder_collection).doc(data.id).update({ 'status': '已完成' })
                        for (obdAndStaff of obdAndStaffs) {
                            await db.collection(obd_collection).where({ _id: obdAndStaff._id }).update({
                                staff: obdAndStaff.newStaffAccount,
                                staffName: obdAndStaff.newStaffName,
                                isNewAdd: "否",
                                grid: wordOrder.grid
                            });
                            // obdID，obd名称，新装维姓名，旧装维姓名，工单号，创建时间
                            await db.collection(obd_modify_collection).add({
                                obd_id: obdAndStaff._id,
                                obdID: obdAndStaff.obdId,
                                obdName: obdAndStaff.fgqmc,
                                oldStaffName: obdAndStaff.oldStaffName,
                                oldStaffAccount: obdAndStaff.oldStaffAccount,
                                newStaffName: obdAndStaff.newStaffName,
                                newStaffAccount: obdAndStaff.newStaffAccount,
                                workOrderId: data.id,
                                grid: wordOrder.grid,
                                createDateTime: common.getDateTime(),
                                workOrderCreator: wordOrder.creator
                            })
                        }
                    }
                    nextProcess = '通知新旧装维'
                }
            }
            update.currentProcess = nextProcess;
            // 工单的转派装维是否被修改
            if (data.obdAndStaff != wordOrder.obdAndStaff) {
                update.obdAndStaff = data.obdAndStaff;
                const woInfo = JSON.parse(wordOrder.obdAndStaff);
                const reqInfo = JSON.parse(data.obdAndStaff);
                changeNewZw = getChangeNewZw(woInfo, reqInfo)
            }
            if (wordOrder.preProcess == '') {
                update.preProcess = wordOrder.preProcess + wordOrder.currentProcess;
            } else {
                update.preProcess = wordOrder.preProcess + ',' + wordOrder.currentProcess;
            }
            // return
        } else {//2.不同意，则可选择驳回到哪个流程
            if (type == '综调发起') {
                if (zdProcess.indexOf(data.disAgreePocess) === -1) {
                    return { "code": 1, message: "驳回流程值不合法", data: wordOrder }
                }
            } else {
                if (bzProcess.indexOf(data.disAgreePocess) === -1) {
                    return { "code": 1, message: "驳回流程值不合法", data: wordOrder }
                }
            }
            preProcess = data.disAgreePocess;
            update.currentProcess = preProcess;
            //删掉disAgreePocess之后的流程
            woPreProcess = wordOrder.preProcess;
            disAgreePocess = data.disAgreePocess
            let index = woPreProcess.indexOf(disAgreePocess)
            if (index !== -1) {
                // 使用slice从开始截取到temp所在位置（包括temp）
                update.preProcess = woPreProcess.slice(0, index);
                console.log('update.preProcess', update.preProcess);
            } else {
                console.log("disAgreePocess流程未在preProcess中找到。");
            }
        }
    } else {//没有agreeOrNot字段，装维确认，工单完成
        update.currentProcess = '装维已确认';
    }
    update.currentPosition = positionOfProcess(update.currentProcess);
    const token = data.token
    const secret = 'shhhhh';
    loginInfo = jwt.verify(token, secret)
    // log字段需要追加日志
    addLog = {
        "dateTime": common.getDateTime(),
        "position": loginInfo.position,
        'approver': loginInfo.account,
        'approverName': loginInfo.name,
    }
    if ('agreeOrNot' in data) { addLog.operate = data.agreeOrNot }
    if ('approveReason' in data) { addLog.operate = addLog.operate + ',' + data.approveReason }
    if (changeNewZw != '') { addLog.operate = addLog.operate + ',' + changeNewZw }
    oldLog = JSON.parse(wordOrder.log);
    newLog = oldLog.concat(addLog)
    update.log = JSON.stringify(newLog);
    update.currentPosition = positionOfProcess(update.currentProcess);
    upRes = await db.collection(workorder_collection).doc(data.id).update(update);
    if (upRes) {
        return { "code": 1, message: "提交审批成功", data: data.id }
    } else {
        return { "code": 0, message: "提交审批失败", data: data.id }
    }
}
function getChangeNewZw(woInfo, reqInfo) {
    operate = '';
    for (wo of woInfo) {
        for (req of reqInfo) {
            if (wo.obdId == req.obdId && wo.newStaffName != req.newStaffName) {
                operate = operate + "分光器名称:“" + wo.fgqmc + "”修改转派装维：从“" + wo.newStaffName + "”改为“" + req.newStaffName + "”；"
            }
        }
    }
    return operate;
}
function obdAndStaffCompare(obj1, obj2) {
    return obj1.obdId === obj2.obdId && obj1.newStaffName !== obj2.newStaffName;
}
function positionOfProcess(Process) {
    // 定义一个映射对象，用于将流程步骤映射到对应的职位
    const processToPosition = {
        "综调发起": "综调",
        "班长审批": "班长",
        "装维站审批": "移动装维站",
        "综调审批": "综调",
        "班长发起": "班长",
        "主管审批": "装维主管",
        "通知新装维": "全职装维",
        "通知新旧装维": "全职装维",
        "装维已确认": "全职装维",
    };
    return processToPosition[Process]
}